<?php defined('SYSPATH') or die('No direct script access.');

class Controller_BoMember extends Controller_BoBase {
	public $auth_required = TRUE;
	protected $modelName = "member";

	public function action_index()
	{
		$this->request->response = $this->baseInfoView("home",$this->modelName);
	}
	
	public function action_bindPage(){
		$view = View::factory("pages/bo/member/member_bind_page");
		$result_mine = DB::query(Database::SELECT, "select id,name from supplier where memberid = ".$_REQUEST["memberid"]." and status <> 'I'" )->execute();
		$result_others = DB::query(Database::SELECT, "select id,name from supplier where memberid <> ".$_REQUEST["memberid"]." and status <> 'I'" )->execute();
		$view->result_mine = $result_mine->as_array();
		$view->result_others = $result_others->as_array();
		exit($view->render());
	}
	
	public function action_bindSupplier(){
		$supplier = ORM::factory("supplier",$_REQUEST["supid"]);
		$supplier->memberid = $_REQUEST["memberid"];
		$supplier->save();
		$this->action_bindPage();
	}
	
	public function action_unBindSupplier(){
		$supplier = ORM::factory("supplier",$_REQUEST["supid"]);
		$supplier->memberid = 0;
		$supplier->save();
		$this->action_bindPage();
	}

	public function action_insertOrUpdatePage(){
		$view = View::factory("pages/bo/member/member_edit_page");
		$view->model = null;
		if (array_key_exists("memberid", $_REQUEST) && !empty($_REQUEST["memberid"])){
			$model = ORM::factory($this->modelName,$_REQUEST["memberid"]);
			$view->model = $model;
		}
		exit($view->render());
	}

	public function action_insertOrUpdate(){
		if (array_key_exists("id", $_REQUEST)){
			$model = ORM::factory($this->modelName,$_REQUEST["id"]);
			if ($model->password != $_REQUEST["password"] && !$this->checkPassword($model->password,$_REQUEST["password"])){
				$_REQUEST["password"] = $this->hash_password($_REQUEST['password']);
			}else{
				$_REQUEST["password"] = $model->password;
			}
			$model->update($_REQUEST);
		}else{
			$_REQUEST["password"] = $this->hash_password($_REQUEST['password']);
			ORM::factory($this->modelName)->insert($_REQUEST);
		}
		Request::$instance->redirect("boMember");
	}

	public function action_show(){
		exit($this->baseInfoView("member/member_page",$this->modelName)->render());
	}
	
	private function checkPassword($password,$requestpassword) {
		$salt = $this->find_salt($password);
		return $password == $this->hash_password($requestpassword,$salt);
	}
}
